<template>
  <el-dialog
    :title="formData.id ? '编辑商品类别' : '新增商品类别'"
    :visible="dialogVisible"
    :before-close="handleClose"
    center
  >
    <el-form
      ref="addEditForm"
      v-loading="isLoading > 0"
      :model="formData"
      :rules="rules"
      label-width="130px"
      class="add-edit-form"
    >
      <el-form-item label="商品类别名称" prop="cate_name">
        <el-input v-model="formData.cate_name" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="formData.sort" placeholder="请填入一个整数，数字越小越靠前" />
      </el-form-item>

      <el-form-item label="是否上线">
        <el-switch
          :value="formData.status === 1"
          active-color="#13ce66"
          inactive-color="#ff4949"
          @change="formData.status = formData.status === 1 ? -1 : 1"
        />
      </el-form-item>

      <el-form-item class="submit-box">
        <el-button type="primary" @click="submitForm()">提交</el-button>
        <el-button v-if="!formData.id" @click="resetForm()">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
const formData = {
  cate_name: '',
  sort: 1,
  status: -1
}
import _ from 'lodash'
import { addOneCateGoods, updateOneCateGoodsById } from '@/api/cate'
export default {
  name: 'CateAddEdit',
  components: {},
  props: {},
  data() {
    return {
      dialogVisible: false,
      isLoading: 0,
      formData: {},
      rules: {
        cate_name: [
          { required: true, message: '不能为空', trigger: ['change', 'blur'] }
        ]
      }
    }
  },
  computed: {},
  watch: {},
  created() {
  },
  mounted() {},
  methods: {
    handleClose() {
      this.dialogVisible = false
    },
    open(row) {
      this.dialogVisible = true
      this.formData = row ? _.cloneDeep(row) : _.cloneDeep(formData)
      this.$nextTick(() => {
        this.$refs.addEditForm.clearValidate()
      })
    },
    resetForm() {
      this.formData = { ...formData }
      this.$refs.addEditForm.resetFields()
    },
    async submitForm() {
      if (this.isLoading > 0) return
      try {
        this.isLoading++
        if (this.formData.id) {
          await updateOneCateGoodsById(this.formData)
        } else {
          await addOneCateGoods(this.formData)
        }
        this.$emit('refresh')
        this.handleClose()
      } finally {
        this.isLoading--
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.submit-box {
  display: flex;
  justify-content: flex-end;
}
</style>
